<?php header("Access-Control-Allow-Origin:*");

if (empty($_ENV)) {
    $WEB_ROOT = dirname(dirname(dirname(dirname(__DIR__))));
    require $WEB_ROOT . "/vendor/autoload.php";
    $dotenv = Dotenv\Dotenv::createImmutable($WEB_ROOT);
    $dotenv->load();
}

if (empty($_ENV)) {
    echo "config file does't exist";exit;
}

try {
    // load app configs
    $appConfigs = require __DIR__ . '/../config/app.config.php';
    $_SERVER['WEB_ROOT'] = $appConfigs['WEB_ROOT'];

    $view = 1;
    require 'SzPublish.class.php';
    require 'server.php';
    $publisher = SzPublish::get();
    $_version = $publisher->getAppVersion();
    $developer = $publisher->getDeveloper();
    unset($publisher);

    $DataArray = $_REQUEST ?? [];
    $bodyData = @file_get_contents('php://input');
    if (!empty($bodyData)) {
        $bodyData = json_decode($bodyData,true) ?? [];
        $DataArray = array_merge($DataArray, $bodyData);
    }

    file_put_contents($_ENV['LOG_ROOT'] . '/pay-request-' . date('Y-m-d') . '.log', json_encode($DataArray) . "\r\n", FILE_APPEND);

    $timestamp = $DataArray['timestamp'];
    $nonce = $DataArray['nonce'];
    $msg = $DataArray['msg'];
    $token = '52d0ee3c031dd';
    $echostr = trim($DataArray['echostr']);
    $signature = $DataArray['signature'];

    $params = array(
        'nonce' => $nonce,
        'timestamp' => $timestamp,
        'msg' => $msg,
        'token' => $token,
    );
    sort($params, SORT_STRING); //按字母升序排序

    $str = implode('', $params);
    $checkSign = sha1($str);
    $flags = ($checkSign === $signature) ? 'true' : 'false';
    file_put_contents($_ENV['LOG_ROOT'] . '/pay-request-' . date('Y-m-d') . ".log", 'checkSign: ' . $checkSign . ' signature: ' . $signature . " {$flags}\r\n\r\n", FILE_APPEND);
    if ($checkSign === $signature) {
        echo $echostr;
    } else {
        ksort($params);
        $str = implode('', $params);
        $checkSign = sha1($str);
        if ($checkSign === $signature) {
            echo $echostr;
        } else {
            exit;
        }
    }

    $version = $_version;
    $ext = $_POST['ext'] ?? '';//扩展信息，json格式
    $getParams = json_decode($ext, true);//ext扩展信息，json格式
    $ver = $getParams['ver'] ?? null;
    if ($ver) {
        $version = $ver;
    }

    if (!file_exists("./index.php")) {
        $version = 'latest';
    }

    require "./index1.php"; // load the index.php of specified app version
} catch (\Exception $exception) {
    file_put_contents($_ENV['LOG_ROOT'] . '/pay-request-' . date('Y-m-d') . '.log', "Exception: {$exception->getMessage()}, File: {$exception->getFile()}, Line: {$exception->getLine()}" . "\r\n", FILE_APPEND);
}

